<script setup lang='ts'>
import { onMounted, ref } from 'vue'
import { onReady } from '@dcloudio/uni-app'
import { getMemberOrderDetails } from '@/services/order'
import type { orderDetailsDto } from '@/types/orderDetails'
import { OrderState, orderStateList } from '@/services/constants'
import { getPayMockAPI, queryWxPayStatusAPI, wxPayAPI } from '@/services/pay'
import type { PayDto } from '@/types/pay'

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
// 弹出层组件
const popup = ref<UniHelper.UniPopupInstance>()
// 取消原因列表
const reasonList = ref([
  '商品无货',
  '不想要了',
  '商品信息填错了',
  '地址信息填写错误',
  '商品降价',
  '其它',
])
// 订单取消原因
const reason = ref('')
// 复制内容
const onCopy = (id: string) => {
  // 设置系统剪贴板的内容
  uni.setClipboardData({ data: id })
}
// 获取页面参数
const query = defineProps<{
  id: string
  orderState: number
}>()

// 获取订单详情
const orderDetail = ref<orderDetailsDto>()
const getOrderDetailData = async () => {
  const res = await getMemberOrderDetails(query.id, query.orderState)
  orderDetail.value = res.data
}

onMounted(() => {
  getOrderDetailData()
})
// 获取页面栈
const pages = getCurrentPages()
// 获取当前页面实例，数组最后一项
const pageInstance = pages.at(-1) as any

// 倒计时结束事件
const onTimeup = () => {
  // 修改订单状态为已取消
  orderDetail.value!.orderStatus = OrderState.YiQuXiao
}

// 订单支付
const payData = ref<PayDto>()
// 弹出层组件
const payPopup = ref<UniHelper.UniPopupInstance>()

// 页面渲染完毕，绑定动画效果
onReady(() => {
  // 动画效果,导航栏背景色
  // pageInstance.animate(
  //   '.navbar', // 选择器
  //   [{ backgroundColor: 'transparent' }, { backgroundColor: '#f8f8f8' }], // 关键帧信息
  //   1000, // 动画持续时长
  //   {
  //     scrollSource: '#scroller', // scroll-view 的选择器
  //     startScrollOffset: 0, // 开始滚动偏移量
  //     endScrollOffset: 50, // 停止滚动偏移量
  //     timeRange: 1000, // 时间长度
  //   },
  // )
  // // 动画效果,导航栏标题
  // pageInstance.animate('.navbar .title', [{ color: 'transparent' }, { color: '#000' }], 1000, {
  //   scrollSource: '#scroller',
  //   timeRange: 1000,
  //   startScrollOffset: 0,
  //   endScrollOffset: 50,
  // })
  // // 动画效果,导航栏返回按钮
  // pageInstance.animate('.navbar .back', [{ color: '#fff' }, { color: '#000' }], 1000, {
  //   scrollSource: '#scroller',
  //   timeRange: 1000,
  //   startScrollOffset: 0,
  //   endScrollOffset: 50,
  // })
})
// 立即支付
const payClick = async () => {
  const res = await getPayMockAPI(query.id)
  payData.value = res.data
  // 关闭弹窗
  popup.value?.close!()
  // 关闭当前页，再跳转支付结果页
  await uni.redirectTo({ url: `/pagesOrder/payment/payment?id=${query.id}` })
}
const aliPopup = ref<UniHelper.UniPopupInstance>()

// 二维码弹出层的开启
const urCode = ref<PayDto>()
let timer: ReturnType<typeof setTimeout> | null = null

// 进行支付选择
const paySelect = async (item: string) => {
  if (item === 'ali') {
    // TODO 支付宝支付
  }
  if (item === 'wx') {
    // 发送微信支付请求
    await uni.navigateTo({
      url: `/pagesOrder/payDetails/payDetails?chId=${orderDetail.value?.careHistory.chId}`,
    })
    // const res = await wxPayAPI(orderDetail.value?.careHistory?.chId)
    // urCode.value = res.data
    // aliPopup.value?.open?.()
    // payPopup.value?.close?.()
    // // 查询支付是否成功
    // timer = setInterval(async () => {
    //   const res = await queryWxPayStatusAPI(orderDetail.value?.careHistory?.chId)
    //   if (res.code === 200) {
    //     aliPopup.value?.close?.()
    //     // 清除定时器
    //     clearInterval(timer)
    //     timer = null
    //     await uni.showToast({ title: '支付成功', icon: 'success', duration: 2000 })
    //     // 进行页面的跳转
    //     await uni.redirectTo({ url: `/pagesOrder/payment/payment?id=${query.id}` })
    //   }
    // }, 3000)
  }
}
</script>

<template>
  <!-- 自定义导航栏: 默认透明不可见, scroll-view 滚动到 50 时展示 -->
  <view class='navbar' :style="{ paddingTop: safeAreaInsets?.top + 'px' }">
    <view class='wrap'>
      <navigator v-if='pages.length>1' open-type='navigateBack' class='back icon-left'></navigator>
      <navigator v-else url='/pages/index/index' open-type='switchTab' class='back icon-home'>
      </navigator>
      <view class='title'>订单详情</view>
    </view>
  </view>
  <scroll-view scroll-y class='viewport' id='scroller'>
    <template v-if='true'>
      <!-- 订单状态 -->
      <view class='overview' :style="{ paddingTop: safeAreaInsets!.top + 20 + 'px' }">
        <!-- 待付款状态:展示去支付按钮和倒计时 -->
        <template v-if='orderDetail?.orderStatus===OrderState.DaiFuKuan'>
          <view class='status icon-clock' style='margin: 40rpx 0'>等待付款</view>
          <view class='button' @tap='payPopup?.open?.()'>去支付</view>
        </template>
        <template v-if='orderDetail?.orderStatus===OrderState.YiQuXiao'>
          <view class='status icon-clock' style='margin: 40rpx 0'>已取消</view>
        </template>
        <!-- 其他订单状态:展示再次购买按钮 -->
        <template v-else>
          <!-- 订单状态文字 -->
          <view class='status'>{{ orderStateList[orderDetail?.orderStatus]?.text }}</view>
          <view class='button-group'>
            <navigator
              hover-class='none'
              class='button navigator'
              url='/pages/index/index'
              open-type='switchTab'
            >
              返回首页
            </navigator>
          </view>
        </template>
      </view>
      <!-- 商品信息 -->
      <view class='goods'>
        <view class='item'>
          <navigator hover-class='none' v-for='(order,index) in orderDetail?.careOrderDtos'
                     :key='order.careOrder.coType'>
            <!--标题-->
            <view style='font-size: 24rpx;margin-top: 10rpx'>
              <text style='color: #27ba9b'>【{{ order.careOrder.coType == 0 ? '药用' : '检测' }}处方】</text>
              <text>【{{ index + 1 }}】</text>
              <text>【处方总额】￥{{ order.careOrder.allAmount }}</text>
            </view>
            <view class='container'>
              <uni-table border stripe emptyText='暂无更多数据' style='table-layout: fixed'>
                <!-- 表头行 -->
                <uni-tr>
                  <uni-th width='5rpx' align='center'>序号</uni-th>
                  <uni-th align='center'>药品名称</uni-th>
                  <uni-th width='5rpx' align='center'>数量</uni-th>
                  <uni-th width='5rpx' align='center'>单价(元)</uni-th>
                  <uni-th width='5rpx' align='center'>金额(元)</uni-th>
                  <uni-th align='center'>备注</uni-th>
                </uni-tr>
                <!-- 表格数据行 -->
                <uni-tr v-for='(item,index) in order.careOrderItems' :key='item.itemId'>
                  <uni-td>{{ index + 1 }}</uni-td>
                  <uni-td>{{ item.itemName }}</uni-td>
                  <uni-td>{{ item.num }}</uni-td>
                  <uni-td>{{ item.price }}</uni-td>
                  <uni-td>{{ item.amount }}</uni-td>
                  <uni-td class='max'>{{ item.remark }}</uni-td>
                </uni-tr>
              </uni-table>
            </view>
          </navigator>
          <!-- 待评价状态:展示按钮 -->
          <view class='action' v-if='orderDetail?.orderStatus===4'>
            <navigator url='' class='button'>去评价</navigator>
          </view>
        </view>
        <!-- 合计 -->
        <view class='total'>
          <view class='row'>
            <view class='text'>应付金额:</view>
            <view class='symbol primary'>{{ orderDetail?.totalMoney.toFixed(2) }}</view>
          </view>
        </view>
      </view>

      <!-- 订单信息 -->
      <view class='detail'>
        <view class='title'>病例信息</view>
        <view class='row'>
          <view class='item'>
            病例编号: {{ query.id }}
            <text class='copy' @tap='onCopy(query.id)'>复制</text>
          </view>
          <view class='item'>创建时间: {{ orderDetail?.careHistory.careTime }}</view>
          <view class='item'>主述：{{ orderDetail?.careHistory.caseTitle }}</view>
          <view class='item'>诊断信息：{{ orderDetail?.careHistory.caseResult }}</view>
          <view class='item'>医生建议：{{ orderDetail?.careHistory.doctorTips }}</view>
          <view class='item'>备注：{{ orderDetail?.careHistory.remark }}</view>
        </view>
      </view>

      <!-- 底部操作栏 -->
      <view class='toolbar-height' :style="{ paddingBottom:  (safeAreaInsets?.bottom+10) + 'px' }"></view>
      <view class='toolbar' :style="{ paddingBottom: safeAreaInsets?.bottom+ 'px' }">
        <!-- 待付款状态:展示支付按钮 -->
        <template v-if='orderDetail?.orderStatus===1'>
          <view class='button primary' @tap='payPopup?.open?.()'>去支付</view>
        </template>
        <!-- 其他订单状态:按需展示按钮 -->
        <template v-else>
          <!-- 待评价状态: 展示去评价 -->
          <navigator :url='`/pagesOrder/score/score?chId=${orderDetail.careHistory.chId}`' hover-class='none'
                     class='button secondary' v-if='orderDetail?.orderStatus===4'>去评价
          </navigator>
          <!-- 待评价/已完成/已取消 状态: 展示删除订单 -->
          <navigator hover-class='none'
                     :url='`/pages/userDetails/userDetails?userId=${orderDetail?.careHistory.userId}`'
                     class='button secondary' v-if='orderDetail?.orderStatus===5'>查看医生信息
          </navigator>
        </template>
      </view>
      <HosNewsList />
    </template>
    <template v-else>
      <!-- 骨架屏组件 -->
      <!--      <PageSkeleton />-->
    </template>

  </scroll-view>

  <!-- 选择支付方式弹窗 -->
  <uni-popup ref='payPopup' background-color='#fff' type='bottom' mode='center' width='600' border-radius='10'
             :mask-close-able='false' closeable>
    <!-- 支付方式 -->
    <view class='popCon'>
      <view class='popTit'>选择您的支付方式</view>
      <view class='popPay'>
        <view class='payItem' @click="paySelect('wx')">
          <u-icon name='weixin-circle-fill' color='#04BE02' size='70'></u-icon>
          <view class='payType'>微信支付</view>
          <u-icon name='checkbox-mark' color='#B21E23' size='40'></u-icon>
        </view>
        <view class='payItem' @click="paySelect('ali')">
          <u-icon name='zhifubao-circle-fill' color='#1678ff' size='70'></u-icon>
          <view class='payType'>支付宝支付</view>
          <u-icon name='checkbox-mark' color='#B21E23' size='40'></u-icon>
        </view>
        <view class='payItem' @click='payClick'>
          <u-icon name='zhifubao-circle-fill' color='#1678ff' size='70'></u-icon>
          <view class='payType'>模拟支付</view>
          <u-icon name='checkbox-mark' color='#B21E23' size='40'></u-icon>
        </view>
      </view>
    </view>
  </uni-popup>

  <!-- 扫码弹出层 -->
  <uni-popup ref='aliPopup' background-color='#fff' type='center' mode='center' width='600' height='600'>
    <HosUqrcode canvas-id='qrcode' :value='urCode?.codeUrl' :options='{ margin: 10 }'></HosUqrcode>
  </uni-popup>
</template>

<style lang='scss'>
page {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

.navbar {
  width: 750rpx;
  color: #000;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 9;
  /* background-color: #f8f8f8; */
  background-color: transparent;

  .wrap {
    position: relative;

    .title {
      height: 44px;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 32rpx;
      /* color: #000; */
      color: transparent;
    }

    .back {
      position: absolute;
      left: 0;
      height: 44px;
      width: 44px;
      font-size: 44rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      /* color: #000; */
      color: #fff;
    }
  }
}

.viewport {
  background-color: #f7f7f8;
}

.overview {
  display: flex;
  flex-direction: column;
  align-items: center;

  line-height: 1;
  padding-bottom: 30rpx;
  color: #fff;
  background-image: url(https://pcapi-xiaotuxian-front-devtest.itheima.net/miniapp/images/order_bg.png);
  background-size: cover;

  .status {
    font-size: 36rpx;
  }

  .status::before {
    margin-right: 6rpx;
    font-weight: 500;
  }

  .tips {
    margin: 30rpx 0;
    display: flex;
    font-size: 14px;
    align-items: center;

    .money {
      margin-right: 30rpx;
    }
  }

  .button-group {
    margin-top: 30rpx;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .button {
    width: 260rpx;
    height: 64rpx;
    margin: 0 10rpx;
    text-align: center;
    line-height: 64rpx;
    font-size: 28rpx;
    color: #27ba9b;
    border-radius: 68rpx;
    background-color: #fff;
  }
}

.shipment {
  line-height: 1.4;
  padding: 0 20rpx;
  margin: 20rpx 20rpx 0;
  border-radius: 10rpx;
  background-color: #fff;

  .locate,
  .item {
    min-height: 120rpx;
    padding: 30rpx 30rpx 25rpx 75rpx;
    background-size: 50rpx;
    background-repeat: no-repeat;
    background-position: 6rpx center;
  }

  .locate {
    background-image: url(https://pcapi-xiaotuxian-front-devtest.itheima.net/miniapp/images/locate.png);

    .user {
      font-size: 26rpx;
      color: #444;
    }

    .address {
      font-size: 24rpx;
      color: #666;
    }
  }

  .item {
    background-image: url(https://pcapi-xiaotuxian-front-devtest.itheima.net/miniapp/images/car.png);
    border-bottom: 1rpx solid #eee;
    position: relative;

    .message {
      font-size: 26rpx;
      color: #444;
    }

    .date {
      font-size: 24rpx;
      color: #666;
    }
  }
}

.goods {
  margin: 20rpx 20rpx 0;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;

  .item {
    padding: 30rpx 0;
    border-bottom: 1rpx solid #eee;

    .navigator {
      display: flex;
      margin: 20rpx 0;

      .container {
        .max {
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
    }

    .cover {
      width: 170rpx;
      height: 170rpx;
      border-radius: 10rpx;
      margin-right: 20rpx;
    }

    .meta {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
      position: relative;
    }

    .name {
      height: 80rpx;
      font-size: 26rpx;
      color: #444;
    }

    .type {
      line-height: 1.8;
      padding: 0 15rpx;
      margin-top: 6rpx;
      font-size: 24rpx;
      align-self: flex-start;
      border-radius: 4rpx;
      color: #888;
      background-color: #f7f7f8;
    }

    .price {
      display: flex;
      margin-top: 6rpx;
      font-size: 24rpx;
    }

    .symbol {
      font-size: 20rpx;
    }

    .original {
      color: #999;
      text-decoration: line-through;
    }

    .actual {
      margin-left: 10rpx;
      color: #444;
    }

    .text {
      font-size: 22rpx;
    }

    .quantity {
      position: absolute;
      bottom: 0;
      right: 0;
      font-size: 24rpx;
      color: #444;
    }

    .action {
      display: flex;
      flex-direction: row-reverse;
      justify-content: flex-start;
      padding: 30rpx 0 0;

      .button {
        width: 200rpx;
        height: 60rpx;
        text-align: center;
        justify-content: center;
        line-height: 60rpx;
        margin-left: 20rpx;
        border-radius: 60rpx;
        border: 1rpx solid #ccc;
        font-size: 26rpx;
        color: #444;
      }

      .primary {
        color: #27ba9b;
        border-color: #27ba9b;
      }
    }
  }

  .total {
    line-height: 1;
    font-size: 26rpx;
    padding: 20rpx 0;
    color: #666;

    .row {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 10rpx 0;
    }

    .symbol::before {
      content: '¥';
      font-size: 80%;
      margin-right: 3rpx;
    }

    .primary {
      color: #cf4444;
      font-size: 36rpx;
    }
  }
}

.detail {
  line-height: 1;
  padding: 30rpx 20rpx 0;
  margin: 20rpx 20rpx 0;
  font-size: 26rpx;
  color: #666;
  border-radius: 10rpx;
  background-color: #fff;

  .title {
    font-size: 30rpx;
    color: #444;
  }

  .row {
    padding: 20rpx 0;

    .item {
      padding: 10rpx 0;
      display: flex;
      align-items: center;
    }

    .copy {
      border-radius: 20rpx;
      font-size: 20rpx;
      border: 1px solid #ccc;
      padding: 5rpx 10rpx;
      margin-left: 10rpx;
    }
  }
}

.toolbar-height {
  height: 100rpx;
  box-sizing: content-box;
}

.toolbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: calc(var(--window-bottom));
  z-index: 1;

  height: 100rpx;
  padding: 0 20rpx;
  display: flex;
  align-items: center;
  flex-direction: row-reverse;
  border-top: 1rpx solid #ededed;
  border-bottom: 1rpx solid #ededed;
  background-color: #fff;
  box-sizing: content-box;

  .button {
    display: flex;
    justify-content: center;
    align-items: center;

    width: 200rpx;
    height: 72rpx;
    margin-left: 15rpx;
    font-size: 26rpx;
    border-radius: 72rpx;
    border: 1rpx solid #ccc;
    color: #444;
  }

  .delete {
    order: 4;
  }

  .button {
    order: 3;
  }

  .secondary {
    order: 2;
    color: #27ba9b;
    border-color: #27ba9b;
  }

  .primary {
    order: 1;
    color: #fff;
    background-color: #27ba9b;
  }
}

.popup-root {
  padding: 30rpx 30rpx 0;
  border-radius: 10rpx 10rpx 0 0;
  overflow: hidden;

  .title {
    font-size: 30rpx;
    text-align: center;
    margin-bottom: 30rpx;
  }

  .description {
    font-size: 28rpx;
    padding: 0 20rpx;

    .tips {
      color: #444;
      margin-bottom: 12rpx;
    }

    .cell {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 15rpx 0;
      color: #666;
    }

    .icon::before {
      content: '\e6cd';
      font-family: 'erabbit' !important;
      font-size: 38rpx;
      color: #999;
    }

    .icon.checked::before {
      content: '\e6cc';
      font-size: 38rpx;
      color: #27ba9b;
    }
  }

  .footer {
    display: flex;
    justify-content: space-between;
    padding: 30rpx 0 40rpx;
    font-size: 28rpx;
    color: #444;

    .button {
      flex: 1;
      height: 72rpx;
      text-align: center;
      line-height: 72rpx;
      margin: 0 20rpx;
      color: #444;
      border-radius: 72rpx;
      border: 1rpx solid #ccc;
    }

    .primary {
      color: #fff;
      background-color: #27ba9b;
      border: none;
    }
  }
}

.popCon {
  padding: 30rpx 60rpx;
  overflow: hidden;
}

.popTit {
  font-size: 32rpx;
  font-weight: bold;
  color: #020202;
  text-align: center;
}

.popPay {
  padding: 40rpx 0;
  overflow: hidden;
}

.payItem {
  padding: 20rpx 0;
  border-bottom: 1rpx solid #eee;
  overflow: hidden;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.payItem .payType {
  flex: 2;
  font-size: 28rpx;
  font-weight: bold;
  margin-left: 20rpx;
}

.popPost {
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
}

.popConfirm {
  width: 220rpx;
  height: 70rpx;
  line-height: 70rpx;
  text-align: center;
  font-size: 30rpx;
  color: #fff;
  background: #b21e23;
  border-radius: 10rpx;
  overflow: hidden;
}
</style>
